<script setup>
import { useRouter, useRoute } from "vue-router";
import { ref, reactive, watch } from "vue";
import request from "../../utils/request";
import { ElMessage, ElNotification } from "element-plus";
import { mavonEditor } from "mavon-editor";
import "mavon-editor/dist/css/index.css";

let md = ref(null);
let img_file = {};
const imgAdd = (pos, $file) => {
  // 缓存图片信息
  img_file[pos] = $file;
  uploadimg();
};
const imgDel = (pos) => {
  delete img_file[pos];
};

const uploadimg = ($e) => {
  // 第一步.将图片上传到服务器.
  var formdata = new FormData();
  for (var _img in img_file) {
    formdata.append("file", img_file[_img]);
  }
  request
    .request({
      url: "/article/imageAdd",
      method: "post",
      data: formdata,
      headers: { "Content-Type": "multipart/form-data" },
    })
    .then((res) => {
      const paths = res.data.data.payload;
      /**
       * 例如：返回数据为 res = [[pos, url], [pos, url]...]
       * pos 为原图片标志（0）
       * url 为上传后图片的url地址
       */
      // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
      for (let index = 0; index < paths.length; index++) {
        md.value.$img2Url(index + 1, paths[index]);
      }
    });
};

let breadList = []; // 路由集合
const route = useRoute();
const router = useRouter();
const getBreadcrumb = (url) => {
  let matched = url.matched;
  //如果不是首页
  if ("Home" == matched[0].name) {
    matched[0].meta = { a_title: "系统首页" };
  }
  breadList = matched;
};
watch(
  route,
  (newValue, oldValue) => {
    // console.log(222222,newValue)
    getBreadcrumb(newValue);
  },
  { deep: true, immediate: true }
);

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
const checka_title = async () => {
  request
    .request({
      url: "/user/add",
      method: "post",
      data: {
        a_title: ruleForm.a_title,
      },
    })
    .then((res) => {
      if (res.data.code == 505) {
        // ElNotification({
        //   a_title: "文章标题已存在",
        //   a_author: "error",
        // });
        ElMessage({
          message: "文章标题已存在",
          a_author: "error",
        });
      }
    });
};
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // console.log("提交更新", fields);
      request
        .request({
          url: "/article/addArticle",
          method: "post",
          data: {
            // u_id: ruleForm.u_id,
            title: ruleForm.a_title,
            // a_desc: ruleForm.a_desc,
            // a_status: ruleForm.a_status,
            content: ruleForm.a_content,
          },
        })
        .then((res) => {
          if (res.data.code == 505) {
            ElNotification({
              a_title: "添加失败",
              message: "文章标题已存在",
              a_author: "error",
            });
          } else if (res.data.code == 200) {
            ElNotification({
              a_title: "添加成功",
              message: "成功添加信息",
              a_author: "success",
            });
            router.push("/articleInfo");
          } else {
            ElNotification({
              a_title: "添加失败",
              message: "一：请联系管理员检查失败原因",
              a_author: "error",
            });
          }
        })
        .catch((e) => {
          ElNotification({
            a_title: "添加失败",
            message: "二：请联系管理员检查失败原因",
            a_author: "error",
          });
        });
    } else {
      ElNotification({
        a_title: "校验失败",
        message: "请重新填写信息",
        a_author: "error",
      });
    }
  });
};
const ruleForm = reactive({
  // u_id: "",
  a_title: "",
  a_desc: "",
  a_status: 1,
  a_content: "",
});
const rules = reactive({
  a_title: [
    {
      required: true,
      message: "请输入文章标题",
      trigger: ["blur", "change"],
    },
    {
      pattern: /^\S*$/, // 正则表达式校验文章标题，不允许空格
      message: "文章标题中不能有空格",
      trigger: ["blur", "change"],
    },
    // {
    //   pattern: /^[a-zA-Z0-9_]+$/, // 正则表达式校验文章标题，只允许字母、数字和下划线
    //   message: "文章标题只能包含字母、数字和下划线",
    //   trigger: ["blur", "change"],
    // },
  ],
  a_desc: [
    {
      required: true,
      message: "请输入简介",
      trigger: ["blur", "change"],
    },
    // {
    //   min: 3,
    //   max: 10,
    //   message: "3≤密码长度≤10",
    //   trigger: ["blur", "change"],
    // },
    // {
    //   pattern: /^(?=.*[A-Za-z])(?=.*\d)(?!.*\s).+$/, // 正则表达式校验密码，至少包含字母和数字，并且不包含空格
    //   message: "密码至少包含字母和数字，且不能含有空格",
    //   trigger: ["blur", "change"],
    // },
  ],

  a_status: [
    {
      required: true,
      message: "请选择文章状态",
      trigger: "change",
    },
  ],
  a_content: [
    {
      required: true,
      message: "请输入文章内容",
      trigger: "change",
    },
  ],
});
const ruleFormRef = ref();
const centerDialogVisible = ref(false);
</script>

<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item
          v-for="(item, index) in breadList"
          :key="index"
          :to="{ path: item.path }"
        >
          {{ item.meta.a_title }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          status-icon
        >
          <el-form-item label="文章标题">
            <el-input v-model="ruleForm.a_title" @blur="checka_title" />
          </el-form-item>
          <el-form-item label="文章简介">
            <el-input v-model="ruleForm.a_desc" />
          </el-form-item>
          <el-form-item label="文章状态">
            <el-radio-group v-model="ruleForm.a_status">
              <el-radio :label="0">停用</el-radio>
              <el-radio :label="1">正常</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="文章内容">
            <!-- <el-input v-model="ruleForm.a_content"  /> -->
            <mavon-editor
              v-model="ruleForm.a_content"
              style="width: 100%"
              ref="md"
              @imgAdd="imgAdd"
              @imgDel="imgDel"
            />
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >新增</el-button
        >
        <el-button @click="resetForm(ruleFormRef)">重置表单</el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>